

//响应拦截器，剥离无用数据，处理token失效
//导出一个函数，调用当前的axios实例发请求
import axios from 'axios';
import store from "@/store";
import router from '@/router'
import { baseURL } from "@/config/index";
import { SET_USER } from "@/store/modules/actionTypes";
//创建一个新的实例
const instance = axios.create({
  baseURL,
  timeout: 30 * 1000
})

//请求拦截器，如果本地有token则带上
instance.interceptors.request.use(config => {
  const { userInfo } = store.state.user
  if (userInfo.token) {
    config.headers.Authorization = `Bear ${userInfo.token}`
  }
  return config
}, err => {
  return Promise.reject(err)
})

//响应拦截器
instance.interceptors.response.use(res => {
  return Promise.resolve(res.data)
}, err => {
  // 401 鉴权失败，token失效
  if (err.response && err.response.status === 401) {
    //1.清空本地用户信息
    store.dispatch(`user/${SET_USER}`, {})
    //2.跳转登陆界面(带上当前页面的参数)
    const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
    router.push(`/login?redirectUrl=${fullPath}`)
    //3.跳转到上一个界面
  }
  return Promise.reject(err)
})

export default (url, method, submit) => {
  return instance({
    url,
    method,
    [method === 'get' ? 'params' : 'data']: submit
  })
}